import { asyncRoutes, constantRoutes } from '@/router'
import { getToken } from '@/utils/auth' // get token from cookie
import { authorityMenu } from '@/api/system/resource'
import Layout from '@/layout/index'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  // if (route.meta && route.meta.roles) {
  //   return roles.some(role => route.meta.roles.includes(role))
  // } else {
  // }
  return true
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      var res = JSON.parse(sessionStorage.getItem('menu_routes'))
      if (res !== null) {
        const loadMenuData = []
        Object.assign(loadMenuData, res.data)
        const tempAsyncRoutes = Object.assign([], asyncRoutes)
        filterAsyncRouter(tempAsyncRoutes, loadMenuData)
        // Object.assign(constant, tempAsyncRoutes)
        // constantRoutes.concat(tempAsyncRoutes)
        commit('SET_ROUTES', tempAsyncRoutes)
        resolve(tempAsyncRoutes)
      } else {
        // 向后端请求路由数据
        authorityMenu(getToken).then(res => {
          sessionStorage.setItem('menu_routes', JSON.stringify(res))
          const loadMenuData = []
          Object.assign(loadMenuData, res.data)
          const tempAsyncRoutes = Object.assign([], asyncRoutes)
          filterAsyncRouter(tempAsyncRoutes, loadMenuData)
          // Object.assign(constant, tempAsyncRoutes)
          // constantRoutes.concat(tempAsyncRoutes)
          commit('SET_ROUTES', tempAsyncRoutes)
          resolve(tempAsyncRoutes)
        }).catch(error => {
          console.log(error)
        })
      }

      // let accessedRoutes
      // // if (roles.includes('admin')) {
      // accessedRoutes = asyncRoutes || []
      // // } else {
      // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // // }
      // commit('SET_ROUTES', accessedRoutes)
      // resolve(accessedRoutes)
    })
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(routes, data) {
  const layout = Layout
  data.forEach((p) => {
    if (p.children !== null && p.children.length > 0) {
      const children = []
      p.children.forEach((ch) => {
        children.push({
          path: ch.uri,
          name: ch.name,
          // component: () => import('@/views/${ch.uri}'),
          component: loadView(ch.uri),
          hidden: ch.isHide === 1,
          meta: { title: ch.name, icon: ch.icon }
        })
      })
      const menus = {
        path: p.uri,
        component: layout,
        redirect: p.uri,
        name: p.name,
        meta: { title: p.name, icon: p.icon },
        alwaysShow: true,
        hidden: p.isHide === 1,
        children: children
      }
      routes.push(menus)
    } else {
      const menus = {
        path: p.uri,
        component: loadView(p.uri),
        redirect: p.uri,
        name: p.name,
        alwaysShow: true,
        hidden: p.isHide === 1,
        meta: { title: p.name, icon: p.icon }
      }
      routes.push(menus)
    }
  })
  // if (route.children != null && route.children && route.children.length) {
  //   route.children = filterAsyncRouter(route.children)
  // }
  // return true
  // routes.push(menus)
}

function loadView(view) {
  // 路由懒加载
  return resolve => require([`@/views${view}`], resolve)// 可以解决
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
